package br.ufrj.dcc.xml.dynamicintervals.encoding;

import java.sql.SQLException;

import org.xml.sax.SAXException;

import br.ufrj.dcc.xml.database.ItemManager;
import br.ufrj.dcc.xml.dynamicintervals.vo.Item;

public class DatabaseEncoder extends SaxEncoder {

	private ItemManager manager;
	
	private String docName;
		
	private int docId;

	public DatabaseEncoder(String docName) {
		super();
		manager = new ItemManager();
		this.docName = docName;
	}
	
	public int getId(){
		return this.docId;
	}

	@Override
	public void startDocument() throws SAXException {
		manager.testDriver();
		try {
			manager.createTables();
		} catch (SQLException e1) {
			// erro esperado quando as tabelas já existem      
		}

		try {
			docId = manager.createDoc(docName);
			manager.getDefaultConnection().setAutoCommit(false);
		} catch (SQLException e) {
			throw new DatabaseException(e);
		}

		super.startDocument();
	}

	@Override
	public void endDocument() throws SAXException {
		try {
			manager.getDefaultConnection().commit();
		} catch (SQLException e) {
			throw new DatabaseException(e);
		}
	}

	@Override
	public void itemGenerated(Item item) throws SAXException {
		try {
			manager.insertItem(docId, item);
		} catch (SQLException e) {
			throw new DatabaseException(e);
		}
	}
	
	public String getOutputText(){
		return manager.getOutputText();
	}
}
